package com.yyl.appx.dao

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.yyl.appx.databinding.ActivityRoomBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RoomActivity : AppCompatActivity() {
    val tag = "MainActivity"
    lateinit var databinding: ActivityRoomBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        databinding = ActivityRoomBinding.inflate(LayoutInflater.from(this))
        setContentView(databinding.root)
        databinding.add.setOnClickListener { add() }
        databinding.deleteV.setOnClickListener { deleteV() }
        databinding.update.setOnClickListener { update() }
        databinding.find.setOnClickListener { find() }
        viewModel.getWorks.observe(this) {
            // adapterListWorks.setWorks(it)
            Log.i(tag, "getWorks=${it.toList()}")
        }
        viewModel.oneToMore.observe(this) {
            // adapterListWorks.setWorks(it)
            Log.i(tag, "oneToMore=${it.toList()}")
        }
    }

    private val viewModel: WorksViewModel by lazy {
        ViewModelProvider(this, ViewModelFactory())
            .get(WorksViewModel::class.java)
    }

    var count = 6
    fun add() {
        count++
        val work = Work(0, "明谷园$count", 10.0 + count)
        val user = User(0, 0, "yyl$count")
        lifecycleScope.launch(Dispatchers.IO) {
            val newId =  viewModel.daoWork.addWork(work)
            user.idWork = newId
            val id =DBTools.instance.daoUsers().addUser(user)
            Log.i(tag, "add =$work   newId=$newId")
        }
//        daoUser.addUser(user)
    }

    fun update() {
        count++
        val work = Work(7, "明谷园$count", 10.0 + count)
        viewModel.addWork(work)
    }

    fun deleteV() {
        lifecycleScope.launch(Dispatchers.IO) {
            viewModel.daoWork.deleteWork(2)
        }
    }


    fun find() {
        lifecycleScope.launch(Dispatchers.IO) {
            viewModel.daoWork.getOneToMore(5)?.let {
                Log.i(tag, "find =$it")
            }?:run{
                Log.i(tag, "find null")
            }
        }

    }

}